package com.fitness.service.serviceimpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.fitness.mapper.PersonMapper;
import com.fitness.mapper.WxMapper;
import com.fitness.model.Address;
import com.fitness.model.Camp;
import com.fitness.model.Classification;
import com.fitness.model.Commodity;
import com.fitness.model.Order;
import com.fitness.model.PrivateTeacher;
import com.fitness.model.Class;
import com.fitness.model.TimeFrame;
import com.fitness.model.WxInformation;
import com.fitness.service.PersonService;
import com.fitness.util.BasicsUtil;
import com.fitness.util.CommonUtil;
import com.fitness.util.DateUtil;
import com.fitness.util.JsonUtil;
import com.fitness.util.MyConfig;
import com.fitness.util.SignUtil;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

@Service
public class PersonServiceImpl implements PersonService{

	@Resource
	PersonMapper personMapper;

	@Resource
	WxMapper wxMapper;
	
	@Override
	public String allTeacher(Class cl) {
		JsonUtil js = new JsonUtil();
		List<Class> list = new ArrayList<Class>();
		list = personMapper.allTeacher(cl);
		if(list!=null || !list.isEmpty()){
			//不为空的情况
			js.setList(list);
			}
		return js.getJson();
	}

	@Override
	public String allTimeFrame(TimeFrame timeFrame) {
		JsonUtil js = new JsonUtil();
		List<TimeFrame> list = new ArrayList<TimeFrame>();
		list = personMapper.allTimeFrame();
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String allClass(Classification classification) {
		JsonUtil js = new JsonUtil();
		List<Classification> list = new ArrayList<Classification>();
		list = personMapper.allClass();
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String privateTeacher(PrivateTeacher privateTeacher) {
		JsonUtil js = new JsonUtil();
		List<PrivateTeacher> list = new ArrayList<PrivateTeacher>();
		list = personMapper.privateTeacher();
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String allCamp(Camp camp) {
		JsonUtil js = new JsonUtil();
		List<Camp> list = new ArrayList<Camp>();
		list = personMapper.allCamp();
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String allFitness(Address address) {
		JsonUtil js = new JsonUtil();
		List<Address> list = new ArrayList<Address>();
		list = personMapper.allFitness(address);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String areaClassify(Address address) {
		JsonUtil js = new JsonUtil();
		List<Address> list = new ArrayList<Address>();
		list = personMapper.areaClassify();
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String fitnessDetail(Address address) {
		if (address.getAid()==null) {
			return JsonUtil.blank(false, 400, "参数错误");
		}
		JsonUtil js = new JsonUtil();
		Address aD = personMapper.fitnessDetail(address);
		js.add(aD);
		return js.getJson();
	}

	@Override
	public String classDetail(Class c) {
		if (c.getTid()==null) {
			return JsonUtil.blank(false, 400, "参数错误");
		}
		JsonUtil js = new JsonUtil();
		Class cD = personMapper.classDetail(c);
		js.add(cD);
		return js.getJson();
	}

	@Override
	public String classLables(Classification c) {
		JsonUtil js = new JsonUtil();
		if (c.getName().equals("all")) {
			List<Classification> list = new ArrayList<Classification>();
			list = personMapper.classAll(c.getDate());
			if(list!=null && !list.isEmpty()){
				//不为空的情况
				js.setList(list);
			}
			return js.getJson();
		}
		List<List<Classification>> arrayList = new ArrayList<List<Classification>>();
		//获取，分割开的标签 存进list
		if (c.getName().contains(",")) {
			List<String> result = Arrays.asList(c.getName().split(","));
				//循环查询课程标签中是否有属于这些的标签
				 for (int i = 0; i < result.size(); i++) {
					List<Classification> list = new ArrayList<Classification>();
					String lable = result.get(i);
					Classification classification = new Classification();
					classification.setName(lable);
					classification.setDate(c.getDate());
					list=personMapper.containLable(classification);
					if (!list.isEmpty() || list!=null) {
						arrayList.add(list);
					}
				}
		}
		if (!c.getName().contains(",")){
			List<Classification> list = new ArrayList<Classification>();
			list=personMapper.containLable(c);
			if (list.isEmpty() || list==null) {
				return js.getJson();
			}
			js.setList(list);
		}
		
		return js.getJson();
	}

	@Override
	public String timeFrame(TimeFrame t) {
		JsonUtil js = new JsonUtil();
		if (t.getTimeframeDetail().equals("all")) {
			List<Classification> list = new ArrayList<Classification>();
			list = personMapper.classAll(t.getDate());
			if(list!=null && !list.isEmpty()){
				//不为空的情况
				js.setList(list);
				return js.getJson();
			}
		}
		List<Class> list = new ArrayList<>();
		String timeframeDetail = t.getTimeframeDetail();
		String [ ] line=timeframeDetail.split("-");
		String startTime = line[0];
		String endTime = line[1];
		t.setStartTime(startTime);
		t.setEndTime(endTime);
		list = personMapper.containTimeFrame(t);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String areaTime(Address a) {
		if (a.getArea()==null) {
			return JsonUtil.blank(false, 400, "参数错误");
		}
		JsonUtil js = new JsonUtil();
		if (a.getArea().equals("all")) {
			List<Classification> list = new ArrayList<Classification>();
			list = personMapper.classAll(a.getDate());
			if(list!=null && !list.isEmpty()){
				//不为空的情况
				js.setList(list);
				return js.getJson();
			}
		}
		List<Class> list = new ArrayList<Class>();
		list = personMapper.areaTime(a);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String classOrder(Order order) {
		JsonUtil js = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.classOrder(order);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String unpaidOrder(Order order) {
		JsonUtil js = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.unpaidOrder(order);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String orderDetail(Order order) {
		Order o = new Order();
		o = personMapper.orderDetail(order);
		JsonUtil js = new JsonUtil();
		js.add(o);
		return js.getJson();
	}

	@Override
	public String classWaiting(Order order) {
		JsonUtil js = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.classWaiting(order);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String classEnd(Order order) {
		JsonUtil js = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.classEnd(order);
		if(list!=null && !list.isEmpty()){
			//不为空的情况
			js.setList(list);
		}
		return js.getJson();
	}

	@Override
	public String campOrder(Order order) {
		JsonUtil js = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.campOrder(order);
		if (!list.isEmpty() || list!=null) {
			js.setList(list);
		}
		return js.getJson();
	}

	@Transactional
	public String wxWallet(Order order,HttpServletRequest request) {
		JsonUtil ju = new JsonUtil();
		Map<String, String> resp = null;
		if(order==null) return JsonUtil.blank(false,CommonUtil.ERROR_NONE, "提交的订单错误");
		String	number32 = BasicsUtil.getOrderNumber32();
		order.setOrderNumber(number32);
		//先准备好一些转换数据-->double-->以分为单位的金额string
		String priceStr =  new Integer(new Double(order.getWallet()).intValue()*100).toString();
		//构建与微信交互的数据
		MyConfig config = new MyConfig();
		WXPay wxpay = new WXPay(config);
		Map<String, String> data = new HashMap<String, String>();
		data.put("body", "会员充值");//这里填入标题 测试的时候打印出金额innerto.getTitle()+priceStr
		data.put("device_info", "WEB");//设备信息
		data.put("fee_type", "CNY");//货币种类
		data.put("total_fee", priceStr);//支付金额 这里先填1分
		data.put("spbill_create_ip", "112.74.62.52");//ip地址
		data.put("notify_url", "http://112.74.62.52:8080/fitnessclass/api/wxpay/back");//支付回调地址 写死
		data.put("trade_type", "JSAPI");  //交易类型 我们默认为JSAPI交易
		data.put("openid",order.getOpenid());//获取支付用户的openid
		data.put("out_trade_no",number32);//传入订单号
		try {
			resp = wxpay.unifiedOrder(data);
			System.out.println(WXPayUtil.mapToXml(resp));
			if("FAIL".equals(resp.get("return_code"))) return JsonUtil.blank(false,CommonUtil.ERROR_HANDLE,"预支付失败");
			resp.put("appid",config.getAppID());
			resp.put("timestamp", DateUtil.getTimeStramp().toString());//构建时间戳
			//resp.put("openid",innerto.getOpenid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//对统一支付再次进行签名
		String paySign = SignUtil.wx_md5(resp);
		resp.replace("sign",paySign);
		ju.setMsg("统一支付获取成功");
		ju.add(resp);
		//数据库操作
		{
	
		//存进订单表
		personMapper.wxOrder(order);
		}
		return ju.getJson();
	}

	@Override
	@Transactional
	public String walletPay(Order order) {
		String number32;
		if(order==null) return JsonUtil.blank(false,CommonUtil.ERROR_NONE, "提交的订单错误");
		if (("").equals(order.getOrderNumber())) {
			number32 = BasicsUtil.getOrderNumber32();
			order.setOrderNumber(number32);
		} else {
			number32 = order.getOrderNumber();
		}
		//查询钱包余额
		WxInformation wxInformation =personMapper.walltBalance(order);
		double wallet = wxInformation.getWallet();
		if (order.getId()==0 ) {
			if (order.getPriceTotle()>wallet) {
				return JsonUtil.blank(false, 400, "钱包余额不足，请充值后支付");
			}else {
				//钱包扣钱
				wxMapper.updateWallet(order);
			}
			order.setTimeDetail(order.getDate()+" "+order.getStartTime());
			//订单数据存进数据库
			wxMapper.insertOrder2(order);
		}
		
		return JsonUtil.blank(true, 200, "付款成功");
	}

	@Override
	public String commodityList(Commodity commodity) {
		JsonUtil jsonUtil = new JsonUtil();
		List<Commodity> list = new ArrayList<Commodity>();
		list = personMapper.commodityList();
		if (list!=null) {
			jsonUtil.setList(list);
		}
		return jsonUtil.getJson();
	}

	@Override
	public String commodityDetail(Commodity commodity) {
		Commodity c = new Commodity();
		c=personMapper.commodityDetail(commodity);
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add(c);
		return jsonUtil.getJson();
	}

	@Override
	public String vipIsorno(WxInformation wxInformation) {
		JsonUtil jsonUtil = new JsonUtil();
		WxInformation w = new WxInformation();
		 w = personMapper.vipIsorno(wxInformation);
		if (w.getIsVip()==0) {
			jsonUtil.setSuccess(false);
		}if (w.getIsVip()==1) {
			jsonUtil.setSuccess(true);
		}
		jsonUtil.add(w);
		return jsonUtil.getJson();
	}

	@Override
	public String commodityOrder(Order order) {
		JsonUtil jsonUtil = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.commodityOrder(order);
		if (list!=null) {
			jsonUtil.setList(list);
		}
		return jsonUtil.getJson();
	}

	@Override
	@Transactional
	public String wxpayBack(HttpServletRequest request) throws Exception {
		// 支付结果通知的xml格式数据
		String notifyData = CommonUtil.inputToString(request);
		MyConfig config = new MyConfig();
		WXPay wxpay = new WXPay(config);
		Map<String, String> notifyMap;
		HashMap<String, String> resultMap = new HashMap<>();
		try {
			notifyMap = WXPayUtil.xmlToMap(notifyData);
			// 转换成map
			if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
				// 签名正确
				String time_end = DateUtil.formatString(notifyMap.get("time_end"));
				notifyMap.put("time_end", time_end);//将转换后的时间替换
				System.out.println(notifyMap.get("time_end"));
				notifyMap.put("out_trade_no", notifyMap.get("out_trade_no"));
				Order order = new Order();
				order.setOrderNumber(notifyMap.get("out_trade_no"));
				//根据订单号拿到openid,充值金额，用户名，订单号
				Order order2  = personMapper.odertGetOpenid(order);
				
				//把openid 存进新的 order对象
				order.setOpenid(order2.getOpenid());
				
				//把openid存进 用户信息对象
				WxInformation wxInformation = new WxInformation();
				wxInformation.setOpenid(order2.getOpenid());
				
				//通过openid 查询 用户详细信息
				WxInformation vipIsorno = personMapper.vipIsorno(wxInformation);
				//用户原有钱包里的钱
				double wallet = vipIsorno.getWallet();
				//充值金额
				double price = order2.getWallet();
				//一共有多少钱
				double p =wallet+price;
				order2.setWallet(p);
				//存进用户钱包
				personMapper.wxWallet(order2);
				wxMapper.updateWxPayBack(order2);//数据库操作
				
				resultMap.put("return_code", "SUCCESS");
				resultMap.put("return_msg", "ok");
				System.out.println(WXPayUtil.mapToXml(resultMap));
				// 进行处理。
				// 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
			}
			else {
				resultMap.put("return_code", "FALT");
				// 签名错误，如果数据里没有sign字段，也认为是签名错误 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return WXPayUtil.mapToXml(resultMap);  
	}

	@Override
	public String fitnessUpdate(Address address) {
		personMapper.fitnessUpdate(address);
		return JsonUtil.blank(true, 200, "修改成功");
	}

	@Override
	public String privateOrderList(Order order) {
		JsonUtil jsonUtil = new JsonUtil();
		List<Order> list = new ArrayList<Order>();
		list = personMapper.privateOrderList(order);
		if (list!=null) {
			jsonUtil.setList(list);
		}
		return jsonUtil.getJson();
	}


}
